<?php
/**
 * 系统设置
 * @since 1.0 <2015-5-26> SoChishun <14507247@qq.com> Added.
 */
include 'function.php';
$config = load_config();
if ('submit' == query('action')) {
    die(json_encode(install_data($config)));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>安装数据-INSTALL</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="//libs.useso.com/js/yui/3.17.2/cssreset/cssreset-min.css" rel="stylesheet" />
        <link href="./Skin/theme-blue.css" rel="stylesheet" />
        <script src="//libs.useso.com/js/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>        
    </head>
    <body class="page-step-setting">
        <div class="header">
            <div class="frame-style">
                <div class="logo"><?php echo $config['APP_NAME'] ?> INSTALL安装向导</div>
                <div class="breadcrumb">
                    <ul>
                        <li><a href="./install.php">欢迎界面</a></li>
                        <li><a href="./step_env.php">环境检测</a></li>
                        <li><a href="./step_setting.php">系统配置</a></li>
                        <li class="cur">初始化数据</li>
                        <li>完成安装</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="bodier">
            <div id="message"></div>
            <form method="post" action="step_data.php" id="frmAdm">
                <section>
                    <h3>管理员信息</h3>
                    <table cellspacing="0" class="table-form">                
                        <tr><th>管理员帐号</th><td><input type="text" name="adm_user" placeholder="管理员帐号" required="required" /></td></tr>
                        <tr><th>管理员密码</th><td><input type="password" name="adm_pwd" placeholder="管理员密码" required="required" /></td></tr> 
                        <tr><th>重复密码</th><td><input type="password" name="adm_repwd" placeholder="重复密码" required="required" /></td></tr>
                        <tr><th>管理员Email</th><td><input type="text" name="adm_email" placeholder="管理员Email" /><em>（用于发送程序错误报告）</em></td></tr>
                    </table>
                </section>
                <section>
                    <h3>附加数据</h3>
                    <div class="checkbox-group">
                        <?php
                        if ($config && !empty($config['db_data_dir'])) {
                            $init_data = $config['db_data_dir'];
                            foreach ($init_data as $key => $text) {
                                echo '<input type="checkbox" name="data[]" value="' . $key . '" />' . $text;
                            }
                        }
                        ?>
                    </div>
                </section>
                <div class="footer">
                    <a href="step_finish.php" id="lnk-submit">下一步</a><a href="#" onclick="return reset_form()">重置</a>
                </div>
                <input type="hidden" name="action" value="submit" />
            </form>
        </div>
        <script type="text/javascript">
            // 2015-5-26 SoChishun Added.
            $('#lnk-submit').click(function () {
                $.ajax({
                    type: 'POST',
                    url: $('#frmAdm').attr('action'),
                    data: $('#frmAdm').serialize(),
                    dataType: 'json',
                    success: function (msg) {
                        console.log(msg);
                        if (msg.status) {
                            location.href = $('#lnk-submit').attr('href');
                        } else {
                            $('#message').html('<div class="red">安装失败 <a href="#" onclick="$(this).next().toggle();return false;">[消息]</a><div style="display:none;">' + msg.info + '</div></div>');
                        }
                    },
                    beforeSend: function () {
                        $('#message').html('<div class="orange">正在安装...</div>');
                    }
                })
                return false;
            })
            function reset_form() {
                document.getElementById('frmAdm').reset();
                return false;
            }
        </script>
    </body>
</html>
<?php

// 获取post数据
function query($name) {
    return isset($_POST[$name]) ? $_POST[$name] : '';
}

/**
 * 加载sql文件为分号分割的数组
 * 支持存储过程和函数提取
 * @param string $path 文件路径
 * @return boolean|array
 * @since 1.0 <2015-5-27> SoChishun Added.
 */
function load_sql_file($path, $fn_splitor = ';;') {
    if (!file_exists($path)) {
        return false;
    }
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $arr = false;
    $str = '';
    $skip = false;
    $fn = false;
    foreach ($lines as $line) {
        $line = trim($line);
        // 过滤注释
        if (!$line || 0 === strpos($line, '--') || 0 === strpos('*') || 0 === strpos($line, '/*') || (false !== strpos($line, '*/') && strlen($line) == (strpos($line, '*/') + 2))) {
            if (!$skip && 0 === strpos($line, '/*')) {
                $skip = true;
            }
            if ($skip && false !== strpos($line, '*/') && strlen($line) == (strpos($line, '*/') + 2)) {
                $skip = false;
            }
            continue;
        }
        if ($skip) {
            continue;
        }
        // 提取存储过程和函数
        if (0 === strpos($line, 'DELIMITER ' . $fn_splitor)) {
            $fn = true;
            continue;
        }
        if (0 === strpos($line, 'DELIMITER ;')) {
            $fn = false;
            $arr[] = $str;
            $str = '';
            continue;
        }
        if ($fn) {
            $str.=$line . ' ';
            continue;
        }
        // 提取普通语句
        $str.=$line;
        if (false !== strpos($line, ';') && strlen($line) == (strpos($line, ';') + 1)) {
            $arr[] = $str;
            $str = '';
        }
    }
    return $arr;
}

function install_data($model_config) {
    $config = isset($_SESSION['suinstall-db-config']) ? $_SESSION['suinstall-db-config'] : false;
    if (!$config) {
        return array('status' => false, 'info' => '数据库连接无效');
    }
    $link = @mysql_connect($config['db_host'], $config['db_user'], $config['db_pwd']);
    if (false === $link) {
        return array('status' => false, 'info' => mysql_error());
    }
    $res = @mysql_select_db($config['db_name']);
    if (false === $res) {
        return array('status' => false, 'info' => mysql_error());
    }
    $res = @mysql_query('SET NAMES UTF8');
    if (false === $res) {
        return array('status' => false, 'info' => mysql_error());
    }
    // 设置MySQL超时时间为1小时
    @mysql_query("SET interactive_timeout = 3600;");
    @mysql_query("SET wait_timeout = 3600;");
    // 写入管理员帐号
    $admin = array('adm_user' => query('adm_user'), 'adm_pwd' => query('adm_pwd'), 'adm_email' => query('adm_email'));
    $sql = sprintf($model_config['db_create_admin_sql'], $admin['adm_user'], $admin['adm_pwd'], $admin['adm_email']);
    $res = @mysql_query($sql);
    if (false === $res) {
        return array('status' => false, 'info' => '[写入管理员]' . mysql_error());
    }
    $_SESSION['suinstall-admin'] = $admin;
    // 写入附加数据
    $datas = query('data');
    foreach ($datas as $path) {
        if (!is_file($path)) {
            return array('status' => false, 'info' => $path . ' 不存在');
        }
        $sqls = load_sql_file($path);
        if ($sqls) {
            $err = false;
            foreach ($sqls as $sql) {
                $res = @mysql_query($sql);
                if (false === $res) {
                    if (!$err || count($err) < 20) { // 防止错误太多,只保留20条错误消息
                        $err[] = $sql . mysql_error();
                    }
                }
            }
            if ($err) {
                return array('status' => false, 'info' => '[写入附加数据]' . implode('<br />', $err));
            }
        }
    }
    // 写入补丁
    if (!empty($model_config['db_patch_dir'])) {
        $dirs = $model_config['db_patch_dir'];
        foreach ($dirs as $path) {
            if (!is_file($path)) {
                return array('status' => false, 'info' => $path . ' 不存在');
            }
            $sqls = load_sql_file($path);
            if ($sqls) {
                $err = false;
                foreach ($sqls as $sql) {
                    $res = @mysql_query($sql);
                    if (false === $res) {
                        if (!$err || count($err) < 20) { // 防止错误太多,只保留20条错误消息
                            $err[] = $sql . mysql_error();
                        }
                    }
                }
                if ($err) {
                    return array('status' => false, 'info' => '[写入补丁]' . implode('<br />', $err));
                }
            }
        }
    }
    return array('status' => true, 'info' => $id);
}
?>
    